﻿using System.Collections.ObjectModel;
using System.IO;
using HalconDotNet;
using MachineVision.Core;
using MachineVision.Core.TemplateMatch;
using MachineVision.Core.TemplateMatch.ShapeModel;
using MachineVision.Core.TemplateMatch.Shared;
using MachineVision.Shared.Controls;
using Microsoft.Win32;
using Prism.Commands;
using Prism.Ioc;
#nullable disable
namespace MachineVision.TemplateMatch.ViewModels
{
    public class ShapeViewModel : NavigationViewModel
    {
        public ShapeModelService MatchService { get; private set; }

        public ShapeViewModel()
        {
            MatchService =
                ContainerLocator.Current.Resolve<ITemplateMatchService>(
                    nameof(TemplateMatchType.ShapeModel)
                ) as ShapeModelService;
            DrawInfos = new ObservableCollection<DrawingObjectInfo>();
        }

        #region CommandFunction
        /// <summary>
        /// 执行
        /// </summary>
        void ExecuteRunCommand()
        {
            try
            {
                MatchService.Run(Image);
                //if (res.IsSuccess)
                //{
                //    MatchResults = res.Results;
                //    Result.Message = res.Message;
                //}
            }
            catch (Exception ex)
            {
                MatchService.MatchResult.Message =
                    $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}:运行出错,{ex.Message}";
            }
        }

        /// <summary>
        /// 创建模板
        /// </summary>
        void ExecuteCreateTemplateCommand()
        {
            try
            {
                var drawobj = DrawInfos.FirstOrDefault()?.DrawObject;
                if (MaskObject != null)
                {
                    HOperatorSet.Difference(drawobj, MaskObject, out HObject regionDifference);
                    MatchService.CreateTemplateAsync(Image, regionDifference);
                    MatchService.MatchResult.Message =
                        $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}:模板创建成功";
                }
                else
                {
                    MatchService.CreateTemplateAsync(Image, drawobj);
                    MatchService.MatchResult.Message =
                        $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}:模板创建成功";
                }
            }
            catch (Exception ex)
            {
                MatchService.MatchResult.Message =
                    $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}:模板创建失败,{ex.Message}";
            }
        }

        /// <summary>
        /// 设置ROI
        /// </summary>
        void ExecuteSetRangedCommand()
        {
            var hobj = DrawInfos.FirstOrDefault();
            if (hobj != null)
            {
                if (hobj.ShapeType == ShapeType.Rectange)
                {
                    MatchService.Roi = new ROIParameter();
                    MatchService.Roi.Row1 = hobj.HTuples[0];
                    MatchService.Roi.Column1 = hobj.HTuples[1];
                    MatchService.Roi.Row2 = hobj.HTuples[2];
                    MatchService.Roi.Column2 = hobj.HTuples[3];
                    MatchService.MatchResult.Message =
                        $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: Roi区域配置完成";
                    DrawInfos.Remove(hobj);
                    return;
                }
            }
            MatchService.Roi = null;
            MatchService.MatchResult.Message =
                $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: 请绘制Roi区域后点击按钮";
        }

        /// <summary>
        /// 加载图像
        /// </summary>
        void ExecuteLoadImageCommand()
        {
            Image?.Dispose();
            DrawInfos?.Clear();

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == true)
            {
                if (File.Exists(ofd.FileName))
                {
                    HObject tmpimage;
                    HOperatorSet.GenEmptyObj(out tmpimage);
                    HOperatorSet.ReadImage(out tmpimage, ofd.FileName);
                    Image = tmpimage;

                    MatchService.MatchResult.Message =
                        $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}:图像加载完成";
                }
            }
        }
        #endregion
        #region Props

        private HObject maskobject;

        public HObject MaskObject
        {
            get { return maskobject; }
            set
            {
                maskobject = value;
                RaisePropertyChanged();
            }
        }

        private ObservableCollection<TemplateMatchResult> matchResults;

        public ObservableCollection<TemplateMatchResult> MatchResults
        {
            get { return matchResults; }
            set
            {
                matchResults = value;
                RaisePropertyChanged();
            }
        }

        private HObject image;

        /// <summary>
        /// 加载的图像
        /// </summary>
        public HObject Image
        {
            get { return image; }
            set
            {
                image = value;
                RaisePropertyChanged();
            }
        }

        private ObservableCollection<DrawingObjectInfo> drawInfos;

        /// <summary>
        /// 绘制的图像集合
        /// </summary>
        public ObservableCollection<DrawingObjectInfo> DrawInfos
        {
            get { return drawInfos; }
            set
            {
                drawInfos = value;
                RaisePropertyChanged();
            }
        }
        #endregion
        #region Command

        private DelegateCommand loadImageCommand;
        public DelegateCommand LoadImageCommand =>
            loadImageCommand ?? (loadImageCommand = new DelegateCommand(ExecuteLoadImageCommand));
        private DelegateCommand runCommand;
        public DelegateCommand RunCommand =>
            runCommand ?? (runCommand = new DelegateCommand(ExecuteRunCommand));
        private DelegateCommand createTemplateCommand;
        public DelegateCommand CreateTemplateCommand =>
            createTemplateCommand
            ?? (createTemplateCommand = new DelegateCommand(ExecuteCreateTemplateCommand));
        private DelegateCommand setRangedCommand;
        public DelegateCommand SetRangedCommand =>
            setRangedCommand ?? (setRangedCommand = new DelegateCommand(ExecuteSetRangedCommand));

        #endregion
    }
}
